import { ajax, transformAjaxData, qsParse } from '@jecloud/utils';
import { useGlobalStore } from '../store/global-store';
import App from '../model/app';

/**
 * 获取启用的第一个App信息
 * @param {*} appId
 * @returns
 */
export function loadApp(appId) {
  const globalStore = useGlobalStore();
  appId = appId || globalStore.appId || '';
  return ajax({
    url: '/je/meta/app/loadApps',
    token: false,
    params: {
      appId,
    },
  })
    .then(transformAjaxData)
    .then((apps) => {
      // 设置app配置信息
      if (apps[0]) {
        const app = new App(apps[0]);
        globalStore.setActiveApp(app);
        return app;
      }
    });
}

/**
 * 校验App
 * @returns
 */
export function validateApp() {
  let appId = '';
  // #ifdef H5
  // 通过地址url参数，判断appId
  const params = qsParse(window.location.href.split('?')[1]);
  appId = params.appId || appId;
  // #endif
  // 请求接口获取启用的第一个app
  return loadApp(appId).then((app) => {
    if (app) {
      return app;
    } else {
      setTimeout(() => {
        // 设置错误信息
        useGlobalStore().appErrorMessage = '无效的AppID，请检查！';
        uni.reLaunch({
          url: '/pages/error/error',
        });
      }, 10);
      return Promise.reject();
    }
  });
}
